const { Success } = require('../../response/code')
const { randStr } = require('../../util/random')
const { createRedisClient } = require('../../util/redis')
const { CAPTCHA_PREFIX } = require('../../consts/system')
const { CAPTCHA_EXPIRE_IN } = process.env
// 引入canvas库
const { createCanvas } = require('canvas')
/**
 * 生成验证码图片
 * @param {*} ctx
 * @param {*} next
 */
const generateCaptcha = async (ctx, next) => {
  // 生成6位验证码
  const captcha = randStr(6)
  const { code } = ctx.request.query
  // 创建canvas
  const canvas = createCanvas(120, 40)
  const ctxCanvas = canvas.getContext('2d')

  // 设置背景色
  ctxCanvas.fillStyle = '#f0f0f0'
  ctxCanvas.fillRect(0, 0, 120, 40)

  // 设置字体和颜色
  ctxCanvas.font = '20px Arial'
  ctxCanvas.fillStyle = '#000'

  // 绘制验证码
  ctxCanvas.fillText(captcha, 20, 25)

  // 添加干扰线
  for (let i = 0; i < 5; i++) {
    ctxCanvas.beginPath()
    ctxCanvas.moveTo(Math.random() * 120, Math.random() * 40)
    ctxCanvas.lineTo(Math.random() * 120, Math.random() * 40)
    ctxCanvas.strokeStyle = '#aaa'
    ctxCanvas.stroke()
  }

  // 将图片转换为base64格式
  const base64Image = canvas.toDataURL()

  const conn = createRedisClient()
  await conn.connect()
  // 存储验证码到redis，过期时间为5分钟
  await conn.set(`${CAPTCHA_PREFIX}:${code}`, captcha, {
    EX: CAPTCHA_EXPIRE_IN || 5 * 60,
  })
  await conn.close()

  // 返回验证码图片的base64数据
  ctx.body = new Success({
    image: base64Image,
  }).toString()
}

module.exports = {
  generateCaptcha,
}
